package com.hjw.httpclient.postdemo;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.springframework.http.HttpStatus;

import java.io.File;
import java.io.IOException;

/**
 * 模拟发送   multipart/form-data 类型的POST请求
 * @author hjwStrart
 * @time 2022-11-21 19:59
 * @version: 1.0
 */
public class Demo3 {
    @Test
    public void method() throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            String urlStr = "http://localhost:8080/form/upload";
            URIBuilder uriBuilder = new URIBuilder(urlStr);
            HttpPost httpPost = new HttpPost(uriBuilder.build());

            // 构造上传文件使用的Entity
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            // 构建 ContentBody 实现类 FileBody对象，用来实现文件上传
            FileBody fileBody = new FileBody(new File("src/main/resources/public/hello.txt"));
            // 构建 ContentBody 实现类 StringBody，用来解决 addTextBody 上传中文乱码问题
            StringBody stringBody = new StringBody("你好",ContentType.create("text/plain",Consts.UTF_8));

            HttpEntity httpEntity = builder.setCharset(Consts.UTF_8)  // 设置编码格式
                    .setContentType(ContentType.create("multipart/form-data", Consts.UTF_8))  //设置Content-Type类型
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) // 设置浏览器模式
                    .addPart("upload",fileBody)    // 添加文件项
                    // addBinaryBody有重载方法，可以传入文件的输入流
                    // addBinaryBody(string,fileinputstream)
                    .addBinaryBody("upload",new File("src/main/resources/public/hello.txt")) // 添加文件项
//                    .addTextBody("userName","你好")  // 添加普通表单项
                    .addPart("userName",stringBody)  // 添加普通表单项
                    .addTextBody("userPwd","123123")   // 添加普通表单项
                    .build();

            httpPost.setEntity(httpEntity);

            httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                System.out.println("请求成功");
            }

        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
